package net.wicp.tams.commons.zookeeper;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.zookeeper.KeeperException;

import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.commons.zookeeper.event.IElection;
import net.wicp.tams.commons.zookeeper.event.State;

/***
 * 领导人选举
 * 
 * @author andy.zhou
 *
 */
public class LeaderElection {

	private final ZKLockManager manager;
	private final IElection election;
	private State state = State.START;

	public LeaderElection(String dir, IElection election) {
		this.manager = new ZKLockManager(dir);
		this.election = election;
	}

	public void makeOffer() {
		try {
			String[] tempAry = manager.lock(null);
			if (ArrayUtils.isNotEmpty(tempAry)) {
				String prePath = tempAry[0];
				if (StringUtil.isNotNull(prePath)) {
					changeState(State.READY);
				} else {
					changeState(State.ELECTED);
				}
			} else {
				changeState(State.FAILED);
			}

		} catch (KeeperException e) {
			changeState(State.FAILED);
			e.printStackTrace();
		} catch (InterruptedException e) {
			changeState(State.FAILED);
			e.printStackTrace();
		}
	}

	public void removeOffer() {
		Result ret = manager.unlock();
		if (ret.isSuc()) {
			changeState(State.STOP);
		} else {
			changeState(State.FAILED);
		}
	}

	public State getState() {
		return this.state;
	}

	public void changeState(State newState) {
		election.DoElection(this.state, newState);
		this.state = newState;
	}

}
